import 'package:flutter/material.dart';

/// 一个用于保持页面状态不被销毁的组件封装。
/// 可用于 `PageView`、`TabBarView` 等切换页面场景。
class KeepAliveWrapper extends StatefulWidget {
  /// 需要被保持状态的子组件
  final Widget? child;

  /// 是否保持状态，默认为 true
  final bool keepAlive;

  const KeepAliveWrapper({
    super.key,
    required this.child,
    this.keepAlive = true,
  });

  @override
  State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child!;
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;

  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    // 当 keepAlive 状态变化时，刷新保持状态
    if (oldWidget.keepAlive != widget.keepAlive) {
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }
}
